#!usr/bin/env python  
# -*- coding:utf-8 _*-
""" 
@author:robot
@file: product_and_consumer.py 
@version:
@time: 2023/04/13 
"""
import asyncio
import random

from geekPythonCore.util import async_run_time


async def consumer(queue, id):
    while True:
        val = await queue.get()
        print(f'{id} get a val: {val}')
        await asyncio.sleep(1)


async def producer(queue, id):
    for i in range(5):
        val = random.randint(1, 10)
        await queue.put(val)
        print(f'{id} put a val: {val}')
        await asyncio.sleep(1)


async def main():
    queue = asyncio.Queue()

    consumer_1 = asyncio.create_task(consumer(queue, 'consumer_1'))
    consumer_2 = asyncio.create_task(consumer(queue, 'consumer_2'))

    producer_1 = asyncio.create_task(producer(queue, 'producer_1'))
    producer_2 = asyncio.create_task(producer(queue, 'producer_2'))

    await asyncio.sleep(5)
    consumer_1.cancel()
    consumer_2.cancel()


    res = await asyncio.gather(
        consumer_1,
        consumer_2,
        producer_1,
        producer_2,
        return_exceptions=True
    )
    print(res)


async_run_time(main)
